package com.zyl.blog.rbac.advice;

import com.zyl.blog.common.handler.DesensitizationHandler;
import com.zyl.blog.common.utils.Extreme.LogUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * 脱敏AOP切面
 * 用于对Controller返回的结果进行自动脱敏处理
 * @version v1.0
 * @ProjectName: Personal_Blog_Server
 * @Package: com.zyl.blog.rbac.advice
 * @ClassName: DesensitizeAop
 * @Author FinalFantasy
 * @Date 2025/9/8-10:25
 */
@Aspect
@Component
public class DesensitizeAop {

    private final DesensitizationHandler desensitizationHandler;

    public DesensitizeAop(DesensitizationHandler desensitizationHandler) {
        this.desensitizationHandler = desensitizationHandler;
    }

    /**
     * 定义切入点：所有Controller的方法
     * 可根据实际项目调整包路径
     */
    @Pointcut("execution(* com.zyl.blog.rbac.web.controller..*(..))")
    public void desensitizePointcut() {}

    /**
     * 环绕通知：对返回结果进行脱敏处理
     */
    @Around("desensitizePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getDeclaringTypeName() + "." + signature.getName();

        LogUtil.info("开始对方法[{}]的返回结果进行脱敏处理", methodName);

        long startTime = System.currentTimeMillis();
        try {
            // 执行原方法
            Object result = joinPoint.proceed();

            // 对结果进行脱敏处理
            Object desensitizedResult = desensitizationHandler.desensitize(result);

            long endTime = System.currentTimeMillis();
            LogUtil.info("方法[{}]的返回结果脱敏处理完成，耗时[{}ms]", methodName, (endTime - startTime));

            return desensitizedResult;
        } catch (Throwable e) {
            LogUtil.error("方法[{}]的返回结果脱敏处理发生异常", null, methodName, e);
            throw e;
        }
    }
}
